package com.apcc4m.sfpushbatch.reader;

import java.util.ArrayList;

import org.springframework.batch.item.database.AbstractPagingItemReader;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.apcc4m.sfpushbatch.repository.Notification;
import com.apcc4m.sfpushbatch.repository.NotificationRepository;

public class NotificationPagingItemReader<T> extends AbstractPagingItemReader<Notification> implements InitializingBean {

    int doReadCount = 1;

    @Autowired
    private NotificationRepository notificationRepository;

    /**
     * 首先执行一遍，执行完后执行doRead方法
     */
    @Override
    protected void doOpen() throws Exception {
        super.doOpen();
        super.setPageSize(10);
        results = new ArrayList<Notification>();
        System.out.println("开始读取Notification数据");
    }

    /**
     * 
     * 从数据库中一条一条读取数据，doRead调用完成后执行ItemWrite类中的write方法，反复不停的调用，如果返回null，则调用doClose
     */
    @Override
    protected Notification doRead() throws Exception {
//        super.doRead();
        System.out.println("正在一条条的读取Notification");
        Notification notification= notificationRepository.findOneByStatusOrderByPushDateAsc(0);
        return notification;
    }

    /**
     * 假设从数据库中检索出50条数据,，每读取10条执行一次doReadPage
     * results结果增加10条数据
     */
    @Override
    protected void doReadPage() {
        System.out.println("doReadPage called" + results.size());
    }

    @Override
    protected void doJumpToPage(int arg0) {
        try {
            super.jumpToItem(arg0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("doJumpToPage called");
    }

    @Override
    protected void doClose() throws Exception {
        super.doClose();
        System.out.println("结束读取Notification");
    }

}
